/**
 * Vue3 组合式API - 请求相关hooks
 */

import { ref, computed, onUnmounted } from 'vue'

/**
 * 通用的异步请求hook
 * @param {Function} apiFn - API函数
 * @param {Object} options - 配置选项
 * @returns {Object} - 返回loading、data、error、execute等
 */
export function useRequest(apiFn, options = {}) {
  const { immediate = false, defaultParams = {}, onSuccess, onError } = options

  const loading = ref(false)
  const data = ref(null)
  const error = ref(null)

  const execute = async (params = {}) => {
    loading.value = true
    error.value = null

    try {
      const result = await apiFn({ ...defaultParams, ...params })
      data.value = result

      if (onSuccess) {
        onSuccess(result)
      }

      return result
    } catch (err) {
      error.value = err

      if (onError) {
        onError(err)
      }

      throw err
    } finally {
      loading.value = false
    }
  }

  // 立即执行
  if (immediate) {
    execute()
  }

  return {
    loading,
    data,
    error,
    execute,
    reset: () => {
      data.value = null
      error.value = null
    }
  }
}

/**
 * 分页请求hook
 * @param {Function} apiFn - API函数
 * @param {Object} options - 配置选项
 * @returns {Object} - 返回分页相关数据和方法
 */
export function usePagination(apiFn, options = {}) {
  const { defaultParams = {}, pageSize = 10 } = options

  const loading = ref(false)
  const refreshing = ref(false)
  const loadingMore = ref(false)
  const list = ref([])
  const total = ref(0)
  const currentPage = ref(1)
  const hasMore = ref(true)
  const finished = ref(false)

  // 加载数据
  const loadData = async (page = 1, isRefresh = false) => {
    const isFirstLoad = page === 1 && !isRefresh && list.value.length === 0

    if (isFirstLoad || isRefresh) {
      loading.value = true
      refreshing.value = isRefresh
    } else if (page > currentPage.value) {
      loadingMore.value = true
    }

    try {
      const params = {
        page,
        pageSize,
        ...defaultParams
      }

      const result = await apiFn(params)

      if (isRefresh || page === 1) {
        list.value = result.data || result.list || []
      } else {
        list.value = [...list.value, ...(result.data || result.list || [])]
      }

      total.value = result.total || 0
      currentPage.value = page

      // 判断是否还有更多数据
      const currentTotal = list.value.length
      hasMore.value = currentTotal < total.value
      finished.value = !hasMore.value

      return result
    } catch (error) {
      console.error('分页加载失败:', error)
      throw error
    } finally {
      loading.value = false
      refreshing.value = false
      loadingMore.value = false
    }
  }

  // 刷新
  const refresh = () => {
    return loadData(1, true)
  }

  // 加载更多
  const loadMore = () => {
    if (!hasMore.value || loadingMore.value) return

    return loadData(currentPage.value + 1)
  }

  // 重置
  const reset = () => {
    list.value = []
    currentPage.value = 1
    hasMore.value = true
    finished.value = false
  }

  return {
    loading,
    refreshing,
    loadingMore,
    list,
    total,
    currentPage,
    hasMore,
    finished,
    loadData,
    refresh,
    loadMore,
    reset
  }
}

/**
 * 定时器hook
 * @param {Function} callback - 回调函数
 * @param {number} interval - 间隔时间(ms)
 * @param {boolean} immediate - 是否立即执行
 * @returns {Object} - 返回控制方法
 */
export function useInterval(callback, interval, immediate = false) {
  const timer = ref(null)
  const isActive = ref(false)

  const start = () => {
    if (isActive.value) return

    isActive.value = true

    if (immediate) {
      callback()
    }

    timer.value = setInterval(() => {
      callback()
    }, interval)
  }

  const stop = () => {
    if (timer.value) {
      clearInterval(timer.value)
      timer.value = null
    }
    isActive.value = false
  }

  const toggle = () => {
    if (isActive.value) {
      stop()
    } else {
      start()
    }
  }

  // 组件卸载时自动清理
  onUnmounted(() => {
    stop()
  })

  return {
    isActive,
    start,
    stop,
    toggle
  }
}

/**
 * 倒计时hook
 * @param {number} seconds - 倒计时秒数
 * @returns {Object} - 返回倒计时相关数据和方法
 */
export function useCountdown(seconds) {
  const timeLeft = ref(seconds)
  const isActive = ref(false)
  const timer = ref(null)

  const start = (duration = seconds) => {
    if (isActive.value) return

    timeLeft.value = duration
    isActive.value = true

    timer.value = setInterval(() => {
      if (timeLeft.value > 0) {
        timeLeft.value--
      } else {
        stop()
      }
    }, 1000)
  }

  const stop = () => {
    if (timer.value) {
      clearInterval(timer.value)
      timer.value = null
    }
    isActive.value = false
  }

  const reset = () => {
    stop()
    timeLeft.value = seconds
  }

  const isFinished = computed(() => timeLeft.value === 0)

  // 组件卸载时自动清理
  onUnmounted(() => {
    stop()
  })

  return {
    timeLeft,
    isActive,
    isFinished,
    start,
    stop,
    reset
  }
}